package de.grosjohann.android.feuerwehr.domain;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import de.grosjohann.android.feuerwehr.type.FMSStatusType;
import de.grosjohann.android.feuerwehr.util.StringUtil;

public class Fahrzeug
  implements Serializable {

  private final String identifier;
  private final String description;
  private final FMSStatusType status;

  private final String location;

  private final Date changeDate;

  public Fahrzeug(JSONObject jsonObj) throws JSONException {
    identifier = jsonObj.getString("kennung");
    description = jsonObj.getString("bezeichnung");
    location = jsonObj.getString("location");

    status = FMSStatusType.valueOf(jsonObj.getInt("status"));

    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
      changeDate = fmt.parse(jsonObj.getString("changeDate"));
    } catch (ParseException ex) {
      throw new JSONException(ex.getMessage());
    }
  }

  public FMSStatusType getStatus() {
    return status;
  }

  public String getIdentifier() {
    return identifier;
  }

  public String getDescription() {
    return description;
  }

  public String getLocation() {
    return location;
  }

  public boolean hasLocation() {
    return StringUtil.isNotEmpty(location);
  }

  public Date getChangeDate() {
    return changeDate;
  }

  @Override
  public String toString() {
    return identifier + ": " + status.name();
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((identifier == null) ? 0 : identifier.hashCode());
    result = prime * result + ((status == null) ? 0 : status.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Fahrzeug other = (Fahrzeug) obj;
    if (identifier == null) {
      if (other.identifier != null)
        return false;
    } else if (!identifier.equals(other.identifier))
      return false;
    if (status != other.status)
      return false;
    return true;
  }
}
